package cn.wolfcode.swagger;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.builders.ParameterBuilder;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
    @Bean
    public Docket productApi() {
        //添加登录的head信息
        ParameterBuilder tokenPar = new ParameterBuilder();
        tokenPar.name("token").description("令牌")
                .modelRef(new ModelRef("string"))
                .parameterType("header").required(false).build();
        List pars = new ArrayList<>();
        pars.add(tokenPar.build());

        return new Docket(DocumentationType.SWAGGER_2).select()
                //扫描的包路径
                .apis(RequestHandlerSelectors.basePackage("cn.wolfcode.controller"))
                //定义要生成文档的API的访问URL路径，路径规则
                .paths(PathSelectors.any()).build().globalOperationParameters(pars)
                //设置访问页面上的一些元素信息
                .apiInfo(metaData());

    }

    private ApiInfo metaData() {
        return new ApiInfoBuilder()
                //标题
                .title("SpringBoot开发的四阶段项目-集成了Swagger2")
                //描述
                .description("前后端分离的分布式架构的项目")
                //版本
                .version("1.0.0")
                .license("Apache License Version 2.0")
                .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0")
                .build();
    }

    //UI页面的配置   http://localhost:8080/swagger-ui.html

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}
